package it.tcm.TeacherClassMate.action;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import it.tcm.TeacherClassMate.beans.MailBean;
import it.tcm.TeacherClassMate.beans.UserBean;
import it.tcm.TeacherClassMate.exceptions.EmailAlreadyException;
import it.tcm.TeacherClassMate.exceptions.UsernameAlreadyException;
import it.tcm.TeacherClassMate.facade.MailManageBase;
import it.tcm.TeacherClassMate.facade.UserManageBase;
import it.tcm.TeacherClassMate.form.CustomerForm;
import it.tcm.TeacherClassMate.util.RandomNumber;
import it.tcm.TeacherClassMate.util.SendMail;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;


public class InsertUserAction extends Action {

	private Logger logger = Logger.getLogger(this.getClass().getName());
	private static DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
	
	/** 
	 * Method execute
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 * 
	 */

	public ActionForward execute(
		ActionMapping mapping,
		ActionForm form,
		HttpServletRequest request,
		HttpServletResponse response) 
	{		
		
		logger.info("INSERT USER");
		 
		// disable any caching by the browser
		response.setHeader("expires","1");
		response.addHeader("Pragma","no-cache");
		response.addHeader("cache-control","no-store");
		response.addHeader("pragma","no-cache");
		
		CustomerForm mcaForm = (CustomerForm)form;	
		String firstname = "";
		String lastname = "";
		String username = "";
		String password = "";
		String email = "";
		String gender = "";
		String country = "";			
			
		if (mcaForm.getFirstname() != null) { firstname = (String)mcaForm.getFirstname(); }
		if (mcaForm.getLastname() != null) { lastname = (String)mcaForm.getLastname(); }
		if (mcaForm.getUsername() != null) { username = (String)mcaForm.getUsername();}
		if (mcaForm.getPassword() != null) { password = (String)mcaForm.getPassword(); }
		if (mcaForm.getEmail() != null) { email = (String)mcaForm.getEmail(); }
		if (mcaForm.getGender() != null) { gender = (String)mcaForm.getGender(); }
		if (mcaForm.getCountry() != null) { country = (String)mcaForm.getCountry(); }
		
		try {		
			 	 
			 Context initial = new InitialContext();		  
			 String admin_emails = (String)initial.lookup("java:comp/env/adminEmails");
			 
			 UserManageBase userManage = new UserManageBase();			
			 List<UserBean> userList = userManage.getUserBeanByEmail(email);			
			 if (userList !=  null && userList.size() > 0) {
				logger.info("email " + email + " is already stored in the database");
				throw new EmailAlreadyException();
			 } else {
				UserBean u = userManage.getUserBeanByUsername(username);
				if (u != null) throw new UsernameAlreadyException();	
				logger.info("storing " + email + " data in the database");
				UserBean user = new UserBean();
				user.setName(firstname);
				user.setSurname(lastname);
				user.setUsername(username);
				user.setPassword(password);
				user.setGender(gender);
				user.setActivated(0);
				user.setEmail(email.toLowerCase());
				user.setCountry(country);			
				if (admin_emails.contains(email)) {
					user.setAdministrator(1);
					logger.info("email " + email + " administrator");
					user.setVerifNum(99999);
				} else {
					logger.info("email " + email + " not of administrator");
					user.setVerifNum(10);
				}
				user.setInTest(1);
				user.setSuspended(0);
				Calendar c1 = Calendar.getInstance(); 
				c1.add(Calendar.YEAR, 1); // add a 1 year
				user.setCode(RandomNumber.generate());
			    userManage.save(user);		    	    
			    logger.info("stored " + email + " in the database");
			    
			    //send mail
				Date todayDate = new Date();
				
				String base_path = (String)initial.lookup("java:comp/env/basePath");
				
				String link = "http://" + base_path + "/activation.do?code=" + user.getCode()+"&user="+user.getId();
				
				String body = "Attivazione utenza www.verificafast.it per " + firstname + " " + lastname + " \n";
				body = body + "Data: " + formatter.format(todayDate) + " \n";
				body = body + "Link : " + link + " \n";			
				
				try {
					//SendMail.sendMail(email,"Attivazione VerificaFast per  " + firstname + " " + lastname,body);
					//logger.info("send message to  " + email + " by mail service");
					MailBean mailBean = new MailBean();
					mailBean.setType("1");
					mailBean.setDest(email);
					mailBean.setBody(body);
					mailBean.setLock("0");
					mailBean.setSent("0");
					mailBean.setFailed(0);
					mailBean.setObject("Attivazione VerificaFast per  " + firstname + " " + lastname);
					MailManageBase mmb = new MailManageBase();
					Integer i = mmb.save(mailBean);
					logger.info("mail with id " + i + " saved");
				} catch (Exception e) {
					logger.error("Exception while saving mail : " + e);
				}
				
			 }
		} catch (UsernameAlreadyException e) {
			logger.error("username is already present in the database");
			return mapping.findForward("usernotinserted"); 
		} catch (EmailAlreadyException e) {
			logger.error("email is already present in the database");
			return mapping.findForward("emailnotinserted"); 
		} catch (Exception e) {
			logger.error("error during insertUserAction");
			return mapping.findForward("usernotinserted"); 
		}
	 
		return mapping.findForward("userinserted"); 
		 
	}
	
	
}